import React, { ReactElement, useRef, useContext, useEffect } from 'react';
import { View, Text, TextInput } from 'react-native';
import Button from '../../../../components/Button';
import { PLACE_HOLDER_GREY } from '../../../../constant/color';
import {
  clickGetVerifyCode,
  clickPasswordLogin,
  guestBindMobilePhone,
  loginWithVerifyCode,
  setPhoneNumber,
  setVerifyCode,
  setVerifyInput
} from '../../actions';
import { Store } from '../../reducer';

import styles from './style';

export default (): ReactElement => {
  const input = useRef<TextInput>(null);
  const verifyInput = useRef<TextInput>(null);

  const { state } = useContext(Store);
  const { phoneNumber, verifyCode, verifyDisabled, verifyText, isBind } = state;

  const canLogin = phoneNumber.length === 11 && verifyCode.length === 4;
  const canInputVerify = !verifyDisabled && phoneNumber.length === 11;

  useEffect((): void => {
    setVerifyInput(verifyInput);
  }, []);

  return (
    <View style={[styles.container, isBind ? styles.smallContainer : {}]}>
      <Text style={styles.title}>若手机号未注册，我们将为您自动注册</Text>
      <View style={styles.loadInputs}>
        <TextInput
          ref={input}
          allowFontScaling={false}
          placeholderTextColor={PLACE_HOLDER_GREY}
          value={phoneNumber}
          style={styles.inputPhone}
          onChangeText={setPhoneNumber}
          placeholder="请输入手机号"
          maxLength={11}
          keyboardType="number-pad"
          autoCapitalize="none"
        />
        <View style={styles.loadInputVerify}>
          <TextInput
            ref={verifyInput}
            allowFontScaling={false}
            placeholderTextColor={PLACE_HOLDER_GREY}
            value={verifyCode}
            style={styles.inputVerify}
            onChangeText={setVerifyCode}
            placeholder="请输入验证码"
            maxLength={4}
            keyboardType="number-pad"
            autoCapitalize="none"
          />
          <Button
            activity={canInputVerify}
            text={verifyText}
            textStyle={[
              styles.verifyDesc,
              phoneNumber.length === 11 ? styles.verifyDescValid : {}
            ]}
            style={[styles.verify, canInputVerify ? styles.verifyValid : {}]}
            onPress={(): void => {
              clickGetVerifyCode();
            }}
          />
        </View>
        <Button
          activity={canLogin}
          text={isBind ? '绑定' : '登录'}
          textStyle={styles.loginDesc}
          style={[styles.login, canLogin ? styles.loginValid : {}]}
          onPress={(): void => {
            if (isBind) {
              guestBindMobilePhone();
              return;
            }
            loginWithVerifyCode();
          }}
        />
      </View>
      {!isBind && (
        <Button
          text="使用密码登录"
          textStyle={styles.changeLoginTypeDesc}
          style={styles.changeLoginType}
          onPress={clickPasswordLogin}
        />
      )}
    </View>
  );
};
